package org.bonorsoft.modules.dingding.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.bonorsoft.common.constant.CommonConstant;
import org.bonorsoft.common.constant.DingdingConstant;
import org.bonorsoft.common.dingapi.DingdingDepart;
import org.bonorsoft.common.system.vo.Ztree;
import org.bonorsoft.common.util.StringUtils;
import org.bonorsoft.common.util.oConvertUtils;
import org.bonorsoft.modules.dingding.entity.SysDepart;
import org.bonorsoft.modules.dingding.entity.SysRole;
import org.bonorsoft.modules.dingding.mapper.SysDepartMapper;
import org.bonorsoft.modules.dingding.mapper.SysRoleDeptMapper;
import org.bonorsoft.modules.dingding.service.ISysDepartService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 组织结构
 * @Author: WilliamYe
 * @Date:   2020-11-13
 * @Version: V1.0
 */
@Service
public class SysDepartServiceImpl extends ServiceImpl<SysDepartMapper, SysDepart> implements ISysDepartService {

    @Resource
    private SysRoleDeptMapper roleDeptMapper;

    /**
     * 根据钉钉部门id获取部门详细信息并存入数据库(添加/更新)
     * @param deptId
     */
    @Override
    public void addOrUpdateDepart(List<Integer> deptId) {
        List<SysDepart> departList = new ArrayList<>();
        for (Integer id:
                deptId) {
            try {
                String result = DingdingDepart.getDepartment(id.longValue());
                String listParent = DingdingDepart.listParentByDept(id.longValue());
                SysDepart depart = JSONUtil.toBean(result, SysDepart.class);
                depart.setAncestors(listParent);
                departList.add(depart);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        this.saveOrUpdateBatch(departList);
    }

    @Override
    public void deleteDepart(List<Integer> deptId) {
        this.removeByIds(deptId);
    }

    /**
     * 查询部门管理树
     *
     * @param dept 部门信息
     * @param req
     * @return 所有部门信息
     */
    @Override
    public List<Ztree> selectDeptTree(SysDepart dept, HttpServletRequest req)
    {
        List<SysDepart> deptList = selectDeptList(dept,req);
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    @Override
    public void hasTopParentDepart() throws Exception{
        int count = this.count(new QueryWrapper<SysDepart>().eq("dept_id", DingdingConstant.PARENT_ID));
        if(count == 0){
            String result = DingdingDepart.getDepartment(DingdingConstant.PARENT_ID);
            SysDepart depart = JSONUtil.toBean(result, SysDepart.class);
            depart.setOrder(-1);
            depart.setAncestors("1");
            this.save(depart);
        }
    }

    /**
     * 判断是否存在子部门
     */
    @Override
    public boolean notHasKidDepart(Long deptId){
        boolean yesOrNo = this.count(new QueryWrapper<SysDepart>().eq("parent_id", deptId))<1;
        return yesOrNo;
    }

    @Override
    public List<SysDepart> queryUserDeparts(String userid) {
        return baseMapper.queryUserDeparts(userid);
    }

    /**
     * 根据角色ID查询部门（数据权限）
     *
     * @param role 角色对象
     * @param request
     * @return 部门列表（数据权限）
     */
    @Override
    public List<Ztree> roleDeptTreeData(SysRole role, HttpServletRequest request) {
        Integer id = role.getId();
        List<Ztree> ztrees;
        List<SysDepart> deptList = selectDeptList(new SysDepart(),request);
        if (StringUtils.isNotNull(id))
        {
            List<String> roleDeptList = roleDeptMapper.selectRoleDeptTree(id);
            ztrees = initZtree(deptList, roleDeptList);
        }
        else
        {
            ztrees = initZtree(deptList);
        }
        return ztrees;
    }

    @Override
    public SysDepart getDepartNameById(Long deptId) {
        return this.getById(deptId);
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysDepart> deptList)
    {
        return initZtree(deptList, null);
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysDepart> deptList, List<String> roleDeptList)
    {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (SysDepart dept : deptList)
        {

            Ztree ztree = new Ztree();
            ztree.setId(dept.getDeptId());
            ztree.setpId(dept.getParentId());
            ztree.setName(dept.getName());
            ztree.setTitle(dept.getName());
            if (isCheck)
            {
                ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getName()));
            }
            ztrees.add(ztree);

        }
        return ztrees;
    }

    /**
     * 获取全部部门
     * @param dept
     * @param req
     * @return
     */
    private List<SysDepart> selectDeptList(SysDepart dept, HttpServletRequest req) {
        QueryWrapper<SysDepart> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("\"ORDER\"");
        String sql = (String) req.getAttribute(CommonConstant.DATA_SCOPE);
        if(oConvertUtils.isNotEmpty(sql)){
            queryWrapper.apply(sql);
        }
        return this.list(queryWrapper);
    }
}
